<?php

/* Edit your database configuration below */

Fluctuate::$conf['db']['type'] = 'mysql';
Fluctuate::$conf['db']['host'] = 'localhost';
Fluctuate::$conf['db']['name'] = 'fluctuate_exemple';
Fluctuate::$conf['db']['user'] = 'root';
Fluctuate::$conf['db']['password'] = '';



/* Edit your data here */

$names = array('"guillemets" doubles et \'simples\'','Neat !','FUNNY !','temps réel !','guitare','Gérard Mouffle','What again ?!');

Fluctuate::assign('maitrises', Fluctuate::dbSelect('* FROM test'));

if( isset( $_REQUEST['id'] ) )
{
	Fluctuate::assign('whereTest', Fluctuate::dbSelect('* FROM test WHERE id='.$_REQUEST['id']));
} else {
	Fluctuate::assign('whereTest', Fluctuate::dbSelect('* FROM test'));
}

Fluctuate::assign('names', $names);
Fluctuate::assign('singleVar', 'hello World !');

Fluctuate::assign('included_html', 'include_example.html', $isFile = true);


/* Controller for the example */

if( isset( $_REQUEST['form_id'] ) )
{
	mysql_query('
	UPDATE test SET
		name="'.mysql_escape_string($_REQUEST['name']).'",
		stuff="'.mysql_escape_string($_REQUEST['stuff']).'",
		text="'.mysql_escape_string($_REQUEST['text']).'"
	WHERE id='.mysql_escape_string($_REQUEST['form_id'])
	) or die(mysql_error());
	
}

/*
 * ****************************************
 * 
 * Don't edit anything below this line, 
 * This is the core of fluctuate
 * 
 * ****************************************
*/

if( isset( $_REQUEST['fluctuate'] ) )
{	
	Fluctuate::renderJson($_REQUEST['fluctuate']);
}


class Fluctuate
{
	static public $data = array();
	static public $conf = array();
		
	public static function dbSelect($string)
	{			
		mysql_connect(self::$conf['db']['host'], self::$conf['db']['user'], self::$conf['db']['password']) or die('Can\'t connect to database.');
		mysql_select_db(self::$conf['db']['name']) or die('Can\'t find the specified database.');
		
		$sqlObject = mysql_query( 'SELECT '.mysql_escape_string( $string ) ) or die('Error while querying database. ');
		
		$sqlArray = array();
	
		while($a = mysql_fetch_assoc( $sqlObject )) { $sqlArray[] = $a; }
		
		foreach($sqlArray as $idLine=>$line)
		{
			foreach($line as $nameField=>$field)
			{
				$sqlArray[$idLine][$nameField] = stripslashes($field);
			}
		}
		
		return $sqlArray;
	}
	
	public static function assign($name, $value, $isFile = false)
	{
		if( $isFile )
			self::$data[$name]['data'] = file_get_contents($value);
		else
			self::$data[$name]['data'] = $value;
	}
	
	public static function renderJson($request)
	{
		header('Cache-Control: no-cache, must-revalidate');
		header('Content-type: application/json');
		
		echo json_encode( self::$data[$request], JSON_FORCE_OBJECT );
		exit();
	}
}

?>
